package com.iqik.base.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

public class NIOClient {

    public static void main(String[] args) {
        // 创建远程地址
        InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8200);
        SocketChannel channel = null;
        // 定义缓存
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try {
            // 开启通道
            channel = SocketChannel.open();
            // 连接远程服务
            channel.connect(address);
            Scanner scanner = new Scanner(System.in);
            while (true) {
                System.out.println("发送数据给服务器");
                String line = scanner.nextLine();
                if (line.equals("exit")) {
                    break;
                }
                // 输入数据写进缓存
                buffer.put(line.getBytes("utf-8"));

                // 重制游标
                buffer.flip();
                // 发送数据
                channel.write(buffer);
                // 清空缓存
                buffer.clear();
                // 接收response数据
                int readLen = channel.read(buffer);
                if (readLen == -1) {
                    break;
                }
                // 重制游标
                buffer.flip();
                byte[] bytes = new byte[buffer.remaining()];
                // 读数据到字节数组
                buffer.get(bytes);
                System.out.println("data: " + new String(bytes, "UTF-8"));
                buffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
